package com.example.week12_networkprogramming;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
   private final int ServerPort = 29898;
   private ServerSocket serverSocket = null;
   private Socket socket = null;
   private OutputStream outputStream = null;
   private InputStream inputStream = null;
   private PrintWriter printWriter = null;
   private BufferedReader reader = null;
   public Server() {
      try {
         serverSocket = new ServerSocket(ServerPort);
         System.out.println("server open...");
         socket = serverSocket.accept();
         System.out.println("kehulianjie...\n");
      } catch (IOException e) { e.printStackTrace();
      }
      try {
         outputStream = socket.getOutputStream();
         inputStream = socket.getInputStream();
         printWriter = new PrintWriter(outputStream, true);
         reader = new BufferedReader(new InputStreamReader(inputStream));
         while (true) {
            String message = reader.readLine();
            System.out.println("message from kehu:" + message);
            if (message.equals("Bye") || message.equals("bye")) break;
            printWriter.println("fuwuqijiehsou");
            printWriter.flush();
         }
         outputStream.close();
         inputStream.close();
         socket.close();
         serverSocket.close();
         System.out.println("kehuclose");
      } catch (IOException e) { e.printStackTrace();
      }
   }
   public static void main(String[] args) {
      new Server();
   }
}